package com.we823.project.controller.manage;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.we823.project.controller.AbstractBaseController;
import com.we823.project.core.web.WebConstants;
import com.we823.project.model.RoleModel;
import com.we823.project.model.UserModel;
import com.we823.project.repository.service.UserService;
import com.we823.project.repository.service.sys.RoleService;
import com.we823.project.repository.service.we.UserRoleService;
import com.we823.utils.web.RequestUtil;


@Controller
@RequestMapping(WebConstants.MANAGE_USER)
public class UserController extends AbstractBaseController<UserModel> {

	private String baseUrl = WebConstants.MANAGE_USER_TEMPLATE;

	private UserService userService;

	@Autowired
	private RoleService roleService;
	@Autowired
	private UserRoleService userRoleService;

	@Autowired
	public UserController(UserService userService) {
		super(userService);
		this.userService = userService;
		super.baseUrl = baseUrl;
		setResourceIdentity("system:user");
	}

	@Override
	public Page<UserModel> getData(PageRequest pageRequest,
			HttpServletRequest request, Model model, boolean pageable) {
		Page<UserModel> userPage = null;
		if (pageable) {
			if (pageRequest != null) {
				userPage = userService.findAll(pageRequest);
			}
		} else {
			userPage = new PageImpl<>(userService.findAll());
		}

		fillInfo(userPage);

		return userPage;
	}

	private void fillInfo(Page<UserModel> userPage) {
		if (userPage != null) {
			List<UserModel> userModels = userPage.getContent();

			for (UserModel userModel : userModels) {
				String roleIds = userModel.getRoleIds();
				if (!StringUtils.isEmpty(roleIds)) {
					StringBuilder stringBuilder = new StringBuilder();
					String[] roleArray = roleIds.split(",");
					if (roleArray != null && roleArray.length > 0) {
						Map<Integer, RoleModel> roleMap = roleService.map();
						int roleArrayLength = roleArray.length;
						for (int index=0;index<roleArrayLength;index++) {
							int roleId = 0;
							try {
								roleId = Integer.parseInt(roleArray[index]);
							} catch (Exception ex) {
								roleId = 0;
							}
							RoleModel roleModel = roleMap.get(roleId);
							if(roleModel!=null) {
								stringBuilder.append(roleModel.getName());
								if(index<roleArrayLength-1) {
									stringBuilder.append(",");
								}
							}
						}
					}
					
					userModel.setRoleNames(stringBuilder.toString());

				}
			}
		}

	}

	@Override
	public String preAdd(HttpServletRequest request, Model model) {
		String result = super.preAdd(request, model);
		
		List<RoleModel> roles = roleService.findAll();
		model.addAttribute("roles", roles);
		return result;
	}

	@Override
	public String add(HttpServletRequest request, UserModel entity,
			Model model, BindingResult bindingResult,RedirectAttributes redirectAttributes) {
		if (entity != null) {
			String password = entity.getPassword();
			password = new Md5Hash(password).toString();
			entity.setPassword(password);

			HttpSession session = request.getSession();
			UserModel currentUserModel = (UserModel) session
					.getAttribute(WebConstants.CURRENT_USER);
			if (currentUserModel != null) {
				entity.setInputer(currentUserModel.getRealname());
			}
			
			String status = entity.getStatus();
			if("正常".equals(status)) {
				entity.setIsblocked(0);
				entity.setIsdeleted(0);
			}else if("删除".equals(status)) {
				entity.setIsblocked(0);
				entity.setIsdeleted(1);
			}else if ("锁定".equals(status)) {
				entity.setIsblocked(1);
				entity.setIsdeleted(0);
			}else {
				entity.setIsblocked(0);
				entity.setIsdeleted(0);
			}
		}
		return super.add(request, entity, model, bindingResult,redirectAttributes);
	}

	@Override
	public String preEdit(HttpServletRequest request, Model model) {

		String result = super.preEdit(request, model);
		List<RoleModel> roles = roleService.findAll();
		model.addAttribute("roles", roles);

		return result;
	}

	@RequestMapping("getRoles")
	@ResponseBody
	public Model getRoles(HttpServletRequest request, Model model) {
		if (permissionList!=null) {
			permissionList.assertHasViewPermission();
		}
		String roleIds = RequestUtil.getValueByParam(request, "roleIds");
		if (!StringUtils.isEmpty(roleIds)) {
			String[] roles = roleIds.split(",");
			model.addAttribute("roleIds", roles);
		}
		return model;
	}

	@Override
	public String edit(HttpServletRequest request, Model model,
			UserModel entity, BindingResult bindingResult,RedirectAttributes redirectAttributes) {
		if (entity != null) {
			String password = entity.getPassword();
			if (StringUtils.isEmpty(password)) {
				UserModel userModel = userService.findOne(entity.getId());
				if (userModel!=null) {
					password = userModel.getPassword();
				}
			}else {
				password = new Md5Hash(password).toString();
			}
			entity.setPassword(password);
		}
		return super.edit(request, model, entity, bindingResult,redirectAttributes);
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public UserRoleService getUserRoleService() {
		return userRoleService;
	}

	public void setUserRoleService(UserRoleService userRoleService) {
		this.userRoleService = userRoleService;
	}

}
